<?php
/**
 * Created by PhpStorm.
 * User: chinanet
 * Date: 2020-01-05
 * Time: 16:14
 */

namespace Francis\PayHelper;

class RSAHelper
{
    public static function rsaSign($data, $private_key_path) {
        $priKey = file_get_contents($private_key_path);
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        //base64编码
        $sign = base64_encode($sign);
        return $sign;
    }

    public static function rsaVerify($data, $ali_public_key_path, $sign) {
        $pubKey = file_get_contents($ali_public_key_path);
        $res = openssl_get_publickey($pubKey);
        $result = openssl_verify($data, base64_decode($sign), $res);
        openssl_free_key($res);
        return $result;
    }

    // RSA解密
    public static function rsaDecrypt($content, $private_key_path) {
        $priKey = file_get_contents($private_key_path);
        $res = openssl_get_privatekey($priKey);
        // 用base64将内容还原成二进制
        $content = base64_decode($content);
        // 把需要解密的内容，按128位拆开解密
        // decrypt the content need to be decrypted by 128 bits
        $result = '';
        for ($i = 0; $i < strlen($content)/128; $i++) {
            $data = substr($content, $i * 128, 128);
            openssl_private_decrypt($data,$decrypt, $res);
            $result .= $decrypt;
        }
        openssl_free_key($res);
        return $result;
    }
}